"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/5/18 14:37
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    permission.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/5/18 14:37 change 'Fix bug'
        
"""
from srf.exceptions import APIException
from srf.permissions import BasePermission
from srf.status import HttpStatus
from srf.utils import run_awaitable

class CheckPermByAnyCode(BasePermission):
    """检查权限，拥有任意一个权限即可"""

    def __init__(self, codes: iter):
        self.codes = codes

    async def has_permission(self, request, view):
        if not request.user.has_permissions(self.codes):
            raise APIException(message='无权限进行此操作', http_status=HttpStatus.HTTP_403_FORBIDDEN)

    async def has_obj_permission(self, request, view, obj):
        pass


def verify_prem(codes, exception=APIException(message='无权限进行此操作', http_status=HttpStatus.HTTP_403_FORBIDDEN)):
    def set_fun(func):
        async def call_fun(view, request, *args, **kwargs):
            if not await request.user.has_permissions(codes):
                raise exception
            return await run_awaitable(func,view, request, *args, **kwargs)
        return call_fun
    return set_fun
